package org.jeecg.modules.wmhb.controller;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.FillRuleConstant;
import org.jeecg.common.constant.UserConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.common.system.vo.SysDepartModel;
import org.jeecg.common.util.FillRuleUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysDepart;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.service.ISysDepartService;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.wmhb.entity.*;
import org.jeecg.modules.wmhb.service.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.wmhb.vo.WmBomResultVo;
import org.jeecg.modules.wmhb.vo.WmFlowDeptVo;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 任务书表
 * @Author: jeecg-boot
 * @Date: 2024-09-06
 * @Version: V1.0
 */
@Api(tags = "任务书表")
@RestController
@RequestMapping("/wmhb/wmTaskbook")
@Slf4j
public class WmTaskbookController extends JeecgController<WmTaskbook, IWmTaskbookService> {
    @Autowired
    private IWmTaskbookService wmTaskbookService;
    @Autowired
    private IWmContractProductService wmContractProductService;
    @Autowired
    private IWmTaskService wmTaskService;
    @Autowired
    private IWmItemService wmItemService;
    @Autowired
    private IWmProductBomService wmProductBomService;
    @Autowired
    private IWmTaskbookFlowService wmTaskbookFlowService;
    @Autowired
    private IWmFlowDeptService wmFlowDeptService;
    @Autowired
    private IWmTaskFlowService wmTaskFlowService;
    @Autowired
    private IWmTaskbookLogService wmTaskbookLogService;
    @Autowired
    private IWmContractService wmContractService;
    @Autowired
    private IWmPurchaseTaskbookBomService wmPurchaseTaskbookBomService;
    @Autowired
    private ISysDepartService sysDepartService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private IWmTaskLogService wmTaskLogService;
    @Autowired
    private IWmTaskBomService wmTaskBomService;
    @Autowired
    private IWmSkillChangeService wmSkillChangeService;

    /**
     * 分页列表查询
     *
     * @param wmTaskbook
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务书-分页列表查询")
    @ApiOperation(value = "任务书-分页列表查询", notes = "任务书-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WmTaskbook>> queryPageList(WmTaskbook wmTaskbook,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<WmTaskbook> queryWrapper = null;
        if(!StringUtils.isEmpty(wmTaskbook.getWmContractProductId())) {
            List<String> contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTaskbook.getWmContractProductId());
            Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
            Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
            newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
            wmTaskbook.setWmContractProductId(null);                                 //清空wmContractProductId=某值的查询条件
            queryWrapper = QueryGenerator.initQueryWrapper(wmTaskbook, newParameterMap);
            queryWrapper.in("wm_contract_product_id", contractProductIdList); //添加清空wmContractProductId in条件
        }
        else{
            queryWrapper = QueryGenerator.initQueryWrapper(wmTaskbook, req.getParameterMap());
        }
        Page<WmTaskbook> page = new Page<WmTaskbook>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmTaskbook> pageList = wmTaskbookService.page(page, queryWrapper);
        List<WmTaskbook> wmTaskbookList = wmTaskbookService.selectTaskbookWithTask(pageList.getRecords());
        pageList.setRecords(wmTaskbookList);
        return Result.OK(pageList);
    }

    /**
     * 分页列表查询（事业部，去除草稿和计划审核不通过的任务）
     *
     * @param wmTaskbook
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "任务书-分页列表查询")
    @ApiOperation(value = "任务书-分页列表查询（事业部）", notes = "任务书-分页列表查询（事业部）")
    @GetMapping(value = "/listByBu")
    public Result<IPage<WmTaskbook>> queryPageListByBu(WmTaskbook wmTaskbook,
                                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                   HttpServletRequest req) {
        QueryWrapper<WmTaskbook> queryWrapper = null;
        String typeOfParam = wmTaskbook.getTaskbookType();
        wmTaskbook.setTaskbookType(null);
        if(!StringUtils.isEmpty(wmTaskbook.getWmContractProductId())) {
            List<String> contractProductIdList = wmContractProductService.selectNodeAndChildren(wmTaskbook.getWmContractProductId());
            Map<String, String[]> parameterMap = req.getParameterMap();              //获取原始的参数映射
            Map<String, String[]> newParameterMap = new HashMap<>(parameterMap);     //创建一个新的HashMap来存储修改后的参数
            newParameterMap.remove("wmContractProductId");                      //删除的参数名是"wmContractProductId"
            wmTaskbook.setWmContractProductId(null);                                 //清空wmContractProductId=某值的查询条件
            queryWrapper = QueryGenerator.initQueryWrapper(wmTaskbook, newParameterMap);
            queryWrapper.in("wm_contract_product_id", contractProductIdList); //添加清空wmContractProductId in条件
        }
        else{
            queryWrapper = QueryGenerator.initQueryWrapper(wmTaskbook, req.getParameterMap());
        }

        if(StringUtils.isEmpty(wmTaskbook.getStatus())) {
            //如果未传状态参数，过滤掉草稿状态的任务书
            queryWrapper.ne("status", UserConstant.TASK_STATUS_PREPARE);
        }

        if(StringUtils.isEmpty(typeOfParam)) {
            //如果未传类型参数，过滤掉设计任务书和采购任务书
            List<String> typeList = new ArrayList<>();
            typeList.add(UserConstant.TASKBOOK_TYPE_DESIGN);
            typeList.add(UserConstant.TASKBOOK_TYPE_PURCHASE);
            queryWrapper.notIn("taskbook_type", typeList);
        }
        else{
            List<String> typeList = Arrays.asList(typeOfParam.split(","));
            queryWrapper.in("taskbook_type", typeList);
            if(typeOfParam.equals("design_taskbook,process_taskbook,debug_taskbook") || typeOfParam.equals("purchase_taskbook,debug_taskbook")){
                //设计管理或采购管理，当前任务书或任务的当前节点部门ID必须在用户所在部门列表中
                LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                List<SysRole> roleList = sysRoleService.queryUserRoles(sysUser.getId());//用户角色
                Boolean isAdminRole = sysRoleService.isAdminRole(roleList);//用户是否有管理员角色
                if(!isAdminRole) {
                    List<String> userDepartIdList = new ArrayList<>();
                    List<SysDepart> departList = sysDepartService.queryUserDeparts(sysUser.getId());
                    for (SysDepart sysDepart : departList) {
                        userDepartIdList.add(sysDepart.getId());
                    }
                    if(!userDepartIdList.isEmpty()) {
                        queryWrapper.in("accept_depart_id", userDepartIdList);
                    }
                    else{
                        return Result.error("您还不属于任何部门");
                    }
                }
            }
        }

        Page<WmTaskbook> page = new Page<WmTaskbook>(pageNo, pageSize);
        queryWrapper.orderByDesc("create_time");
        IPage<WmTaskbook> pageList = wmTaskbookService.page(page, queryWrapper);
        List<WmTaskbook> wmTaskbookList = wmTaskbookService.selectTaskbookWithTask(pageList.getRecords());
        pageList.setRecords(wmTaskbookList);
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param wmTaskbook
     * @return
     */
    @AutoLog(value = "任务书-添加")
    @ApiOperation(value = "任务书-添加", notes = "任务书-添加")
    @RequiresPermissions("wmhb:wm_taskbook:add")
    @PostMapping(value = "/add")
    @Transactional
    public Result<String> add(@RequestBody WmTaskbook wmTaskbook) {
        if(StringUtils.isEmpty(wmTaskbook.getWmContractProductId())){
            return Result.error("请选择合同产品！");
        }

        List<SelectTreeModel> selectTreeModelList = wmContractProductService.queryListByPid(wmTaskbook.getWmContractProductId());
        if(!CollectionUtils.isEmpty(selectTreeModelList)){
            throw new RuntimeException("只能在子节点上新建该任务书");
        }

        //任务书流程部门列表
        if(StringUtils.isEmpty(wmTaskbook.getWmTaskbookFlowId())){
            throw new RuntimeException("请选择任务书类型");
        }

        //判断如果同流程下同一产品是否已有任务书
        WmTaskbook wmTaskbookExist = wmTaskbookService.selectByFolwAndContract(wmTaskbook.getWmTaskbookFlowId(), wmTaskbook.getWmContractProductId());
        if(wmTaskbookExist != null){
            throw new RuntimeException("当前事业部对该产品已新建过同类型任务书");
        }
        //判断合同状态是否能新建任务书
        WmContract wmContract = wmContractService.getById(wmTaskbook.getWmContractId());
        if(wmContract != null && wmContract.getStatus().equals(UserConstant.CONTRACT_STATUS_PREPARE)){
            return Result.error("请先确认合同");
        }

        if(StringUtils.isEmpty(wmTaskbook.getWeight())){
            wmTaskbook.setWeight("1");
        }

        WmContractProduct wmContractProduct = wmContractProductService.getById(wmTaskbook.getWmContractProductId());
        wmTaskbookService.saveTaskbookAndTask(wmTaskbook, wmContractProduct);

        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param wmTaskbook
     * @return
     */
    @AutoLog(value = "任务书-编辑")
    @ApiOperation(value = "任务书-编辑", notes = "任务书-编辑")
    @RequiresPermissions("wmhb:wm_taskbook:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> edit(@RequestBody WmTaskbook wmTaskbook) {
        WmTaskbook wmTaskbookRow = wmTaskbookService.getById(wmTaskbook.getId());
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PREPARE);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        if (!statusList.contains(wmTaskbookRow.getStatus())) {
            //throw new RuntimeException("当前状态不能修改");
        }
        if(StringUtils.isEmpty(wmTaskbook.getWeight())){
            wmTaskbook.setWeight("1");
        }
        wmTaskbookService.updateById(wmTaskbook);

        //任务时间更新
        WmTask rootTask = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(rootTask);
        for(WmTask wmTask: wmTaskList){
            if(!rootTask.getId().equals(wmTask.getId())) {
                //非根任务，如果没有设置计划时间，则和任务书时间保持一致，否则保持自己的设置时间
                if (wmTask.getPlanBeginTime() == null) {
                    wmTask.setPlanBeginTime(wmTaskbook.getPlanBeginTime());
                }
                if (wmTask.getPlanEndTime() == null) {
                    wmTask.setPlanEndTime(wmTaskbook.getPlanEndTime());
                }
            }
            else {
                //根任务的计划时间始终和任务书的计划时间一致
                if (wmTaskbook.getPlanBeginTime() != null){
                    wmTask.setPlanBeginTime(wmTaskbook.getPlanBeginTime());
                }
                if (wmTaskbook.getPlanEndTime() != null){
                    wmTask.setPlanEndTime(wmTaskbook.getPlanEndTime());
                }
                wmTask.setChargeBy(wmTaskbook.getChargeBy());
                wmTask.setWeight(wmTaskbook.getWeight());
                wmTask.setPlanWorkHour(wmTaskbook.getPlanWorkHour());
            }
            wmTaskService.updateById(wmTask);
        }

        //更新任务流程部门信息
        if(!wmTaskbook.getWmTaskFlowList().isEmpty()){
            for(WmTaskFlow wmTaskFlow: wmTaskbook.getWmTaskFlowList()) {
                if(!StringUtils.isEmpty(wmTaskFlow.getId())) {
                    wmTaskFlowService.updateById(wmTaskFlow);
                }
            }
        }
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务书-通过id删除")
    @ApiOperation(value = "任务书-通过id删除", notes = "任务书-通过id删除")
    @RequiresPermissions("wmhb:wm_taskbook:delete")
    @DeleteMapping(value = "/delete")
    @Transactional
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (wmTaskbookService.checkHasItem(id) && !wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PREPARE)) {
            return Result.error("任务书下有任务，请先删除任务");
        }
        else if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PREPARE)){
            wmTaskService.deleteByTaskbookId(id);
        }

        wmTaskbookService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务书-批量删除")
    @ApiOperation(value = "任务书-批量删除", notes = "任务书-批量删除")
    @RequiresPermissions("wmhb:wm_taskbook:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        List<String> oldIdList = Arrays.asList(ids.split(","));
        List<String> newIdList = new ArrayList<>();
        List<String> filterIdList = new ArrayList<>();
        for (String id : oldIdList) {
            if (!wmTaskbookService.checkHasItem(id)) {
                newIdList.add(id);
            } else {
                filterIdList.add(id);
            }
        }

        String filterStr = String.join(",", filterIdList);
        if (!CollectionUtils.isEmpty(newIdList)) {
            this.wmTaskbookService.removeByIds(newIdList);
            if (CollectionUtils.isEmpty(filterIdList)) {
                return Result.OK("批量删除成功！");
            } else {
                String newStr = String.join(",", newIdList);
                return Result.OK("ID为" + newStr + "批量删除成功，ID为" + filterStr + "的删除失败，原因：任务书下有任务！");
            }
        } else {
            return Result.error("批量删除失败，原因：任务书下有任务！");
        }
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "任务书-通过id查询")
    @ApiOperation(value = "任务书-通过id查询", notes = "任务书-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WmTaskbook> queryById(@RequestParam(name = "id", required = true) String id) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (wmTaskbook == null) {
            return Result.error("未找到对应数据");
        }

        wmTaskbook = wmTaskbookService.selectTaskbookWithTask(wmTaskbook);
        return Result.OK(wmTaskbook);
    }

    /**
     * 通过id查询需要展开的节点
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "任务书-通过id查询需要展开的节点", notes = "任务书-通过id查询需要展开的节点")
    @GetMapping(value = "/getExpandKeysById")
    public Result<List<String>> getExpandKeysById(@RequestParam(name = "id", required = true) String id) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (wmTaskbook == null) {
            return Result.error("未找到对应数据");
        }

        List<String> keyList = wmTaskbookService.getExpandKeys(wmTaskbook);
        return Result.OK(keyList);
    }

    /**
     * 计划确认
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务书-计划确认")
    @ApiOperation(value = "任务书-计划确认", notes = "任务书-计划确认")
    @RequiresPermissions("wmhb:wm_taskbook:confirm")
    @RequestMapping(value = "/confirm", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> doConfirm(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
            String nextStatus = "";
            List<String> statusList = new ArrayList<>();
            statusList.add(UserConstant.TASK_STATUS_PREPARE);
            statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
            statusList.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
            statusList.add(UserConstant.TASK_STATUS_PURCHASE_UNAPPROVED);
            statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED_OF_SKILL);
            if (!statusList.contains(wmTaskbook.getStatus())) {
                throw new RuntimeException("当前状态不能确认");
            }
            if(wmTaskbook.getPlanBeginTime() == null || wmTaskbook.getPlanEndTime() == null){
                throw new RuntimeException("计划时间不能为空");
            }

            //如果是采购任务书，必须上传采购清单
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE) || wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)){
                List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskbookId(id);
                if(wmPurchaseTaskbookBomList.isEmpty()){
                    throw new RuntimeException("请上传采购清单");
                }
            }

            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED_OF_SKILL)) {
                nextStatus = UserConstant.TASK_STATUS_PLAN_APPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_PLAN_APPROVED;
            }
            wmTaskbook.setStatus(nextStatus); //更新任务书的状态为计划已审核
            wmTaskbook.setProgress("10");//计划确认算完成10%
            wmTaskbook.setFactBeginTime(new Date());
            wmTaskbook.setConfirmTime(new Date());
            //任务书流程部门列表，确认之后进入下一个流程
            nextFlowTaskbook(wmTaskbook);

            //任务流程时间
            WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
            List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
            wmTaskFlowService.updateFactBeginTimeByStep(wmTaskList, 0);

            //任务书根任务状态改为和任务书状态一致
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("10");//计划确认算完成10%
                wmTaskItem.setStatus(nextStatus); //更新任务的状态为完成
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);

                //更新任务日志
                wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_CONFIRM);
            }
        }
        return Result.OK("操作成功");
    }

    /**
     * 生产办公室对计划部下达的计划进行审批
     *
     * @param id
     * @param result
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-生产办公室审批")
    @ApiOperation(value = "任务书-生产办公室审批", notes = "任务书-生产办公室审批")
    @RequiresPermissions("wmhb:wm_taskbook:produceAapproval")
    @RequestMapping(value = "/produceAapproval", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> produceAapproval(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "result", required = true, defaultValue = UserConstant.APPROVAL_AGREE) String result, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (!wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PLAN_APPROVED)) {
            throw new RuntimeException("只有计划审批通过状态能确认");//生产任务书
        }

        WmTaskbookLog wmTaskbookLog = new WmTaskbookLog();
        wmTaskbookLog.setDepartId(wmTaskbook.getCurrentNodeId());
        wmTaskbookLog.setWmTaskbookId(id);
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        if(!StringUtils.isEmpty(result) && result.equals(UserConstant.APPROVAL_AGREE)) {
            wmTaskbook.setStatus(UserConstant.TASK_STATUS_PRODUCE_APPROVED); //更新任务书的状态为生产审批已通过
            wmTaskbook.setProgress("20");//生产确认算完成20%
            wmTaskbook.setFactBeginTime(new Date());
            wmTaskbook.setApproveTime(new Date());
            wmTaskbook.setAcceptDepartId(wmTaskbook.getCurrentNodeId());
            //任务书根任务状态改为和任务书状态一致 任务书根任务状态改为和任务书状态一致 不能放到nextFlowTask()方法后面执行，不然数据又回退了，因为nextFlowTask方法里面有更改任务信息
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("20");//生产确认算完成20%
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);

                //更新任务日志
                wmTaskLogService.updateTaskLog(wmTaskItem.getId(), UserConstant.TASK_LOG_TYPE_APPROVE);
            }
            wmTaskbookLog.setCheckResult("生产审批已通过");
            //任务书流程部门列表，确认之后进入下一个流程
            nextFlowTaskbook(wmTaskbook);
        }
        else{
            wmTaskbook.setStatus(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED); //更新任务书的状态为生产审批不通过
            wmTaskbook.setProgress("5");//生产审批不通过算完成5%
            //任务书根任务状态改为和任务书状态一致 不能放到prevFlowTask()方法后面执行，不然数据又回退了，因为prevFlowTask方法里面有更改任务信息
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("5");//生产审批不通过算完成5%
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
                wmTaskService.updateById(wmTaskItem);
            }
            wmTaskbookLog.setCheckResult("生产审批不通过");
            //任务书流程部门列表，返回上一流程
            prevFlowTaskbook(wmTaskbook);
        }

        if(!StringUtils.isEmpty(remark)){
            wmTaskbookLog.setContent(remark);
        }
        wmTaskbookLogService.save(wmTaskbookLog);

        return Result.OK("操作成功");
    }

    /**
     * 任务书下一流程
     * @param wmTaskbook
     * @return
     */
    private void nextFlowTaskbook(WmTaskbook wmTaskbook){
        //根据流程ID查找流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
        Integer nextIndex = wmTaskbook.getCurrentNodeIndex() + 1;
        if(nextIndex >= wmFlowDeptList.size()){
            throw new RuntimeException("请补充完整的流程定义");
        }
        wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(nextIndex).getDeptId());
        wmTaskbook.setCurrentNodeIndex(nextIndex);
        wmTaskbookService.updateById(wmTaskbook);

        nextFlowTask(wmTaskbook);
    }

    /**
     * 任务书上一流程
     * @param wmTaskbook
     * @return
     */
    private void prevFlowTaskbook(WmTaskbook wmTaskbook){
        //根据流程ID查找流程部门列表
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
        Integer prevIndex = wmTaskbook.getCurrentNodeIndex() - 1;
        if(prevIndex < 0){
            throw new RuntimeException("流程异常");
        }
        wmTaskbook.setCurrentNodeId(wmFlowDeptList.get(prevIndex).getDeptId());
        wmTaskbook.setCurrentNodeIndex(prevIndex);
        wmTaskbookService.updateById(wmTaskbook);

        prevFlowTask(wmTaskbook);
    }

    /**
     * 任务下一流程(任务书下所有任务都更新)
     * @param wmTaskbook
     * @return
     */
    private void nextFlowTask(WmTaskbook wmTaskbook){
        //更新任务书下所有任务到下一个流程
        LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTask::getCurrentNodeId, wmTaskbook.getCurrentNodeId());
        updateWrapper.set(WmTask::getCurrentNodeIndex, wmTaskbook.getCurrentNodeIndex());
        updateWrapper.set(WmTask::getCurrentNodeTime, new Date());
        updateWrapper.set(WmTask::getStatus, wmTaskbook.getStatus());
        if (wmTaskbook.getCurrentVersion() == null) {
            updateWrapper.isNull(WmTask::getCurrentVersion);
        }
        else {
            updateWrapper.eq(WmTask::getCurrentVersion, wmTaskbook.getCurrentVersion());
        }
        updateWrapper.eq(WmTask::getWmTaskbookId, wmTaskbook.getId());
        wmTaskService.update(null, updateWrapper);

        //获取任务书下所有任务
        Integer currIndex = wmTaskbook.getCurrentNodeIndex(); //当前索引已经是下一流程
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for(WmTask wmTask: wmTaskList){
            //设置上一流程实际结束时间和当前流程实际开始时间
            WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex-1);
            WmTaskFlow wmTaskFlowNext = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex);
            wmTaskFlowCurr.setFactEndTime(new Date());
            wmTaskFlowNext.setFactBeginTime(new Date());
            wmTaskFlowService.updateById(wmTaskFlowCurr);
            wmTaskFlowService.updateById(wmTaskFlowNext);
        }
    }

    /**
     * 任务上一流程
     * @param wmTaskbook
     * @return
     */
    private void prevFlowTask(WmTaskbook wmTaskbook){
        //更新任务书下所有任务到上一个流程
        LambdaUpdateWrapper<WmTask> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(WmTask::getCurrentNodeId, wmTaskbook.getCurrentNodeId());
        updateWrapper.set(WmTask::getCurrentNodeIndex, wmTaskbook.getCurrentNodeIndex());
        updateWrapper.set(WmTask::getCurrentNodeTime, new Date());
        if (wmTaskbook.getCurrentVersion() == null) {
            updateWrapper.isNull(WmTask::getCurrentVersion);
        }
        else {
            updateWrapper.eq(WmTask::getCurrentVersion, wmTaskbook.getCurrentVersion());
        }
        updateWrapper.eq(WmTask::getWmTaskbookId, wmTaskbook.getId());
        wmTaskService.update(null, updateWrapper);

        //获取任务书下所有任务
        Integer currIndex = wmTaskbook.getCurrentNodeIndex();//当前索引已经是上一流程
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbook.getId(), wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for(WmTask wmTask: wmTaskList){
            //设置上一流程实际结束时间和当前流程实际开始时间
            WmTaskFlow wmTaskFlowPrev = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex);
            WmTaskFlow wmTaskFlowCurr = wmTaskFlowService.getTaskFlowByTaskAndOrder(wmTask.getId(), currIndex+1);
            wmTaskFlowPrev.setFactEndTime(null);
            wmTaskFlowCurr.setFactBeginTime(null);
            wmTaskFlowService.updateById(wmTaskFlowPrev);
            wmTaskFlowService.updateById(wmTaskFlowCurr);
        }
    }

    /**
     * 技术审批（技术部领导对任务书的审批）
     *
     * @param id
     * @param result
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-技术审批")
    @ApiOperation(value = "任务书-技术审批", notes = "任务书-技术审批")
    @RequiresPermissions("wmhb:wm_taskbook:technologyAapproval")
    @Transactional
    @RequestMapping(value = "/technologyAapproval", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> technologyAapproval(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "result", required = true, defaultValue = UserConstant.APPROVAL_AGREE) String result, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_SKILL_CHANGE);
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED_OF_SKILL);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("当前状态无法审批");//设计任务书
        }

        WmTaskbookLog wmTaskbookLog = new WmTaskbookLog();
        wmTaskbookLog.setDepartId(wmTaskbook.getCurrentNodeId());
        wmTaskbookLog.setWmTaskbookId(id);
        String nextStatus = "";
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        if(!StringUtils.isEmpty(result) && result.equals(UserConstant.APPROVAL_AGREE)) {
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_SKILL_CHANGE) || wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PLAN_APPROVED_OF_SKILL)) {
                nextStatus = UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED;
            }
            wmTaskbook.setStatus(nextStatus);
            wmTaskbook.setProgress("20");//技术确认算完成20%
            wmTaskbook.setFactBeginTime(new Date());
            wmTaskbook.setApproveTime(new Date());
            wmTaskbook.setAcceptDepartId(wmTaskbook.getCurrentNodeId());

            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(nextStatus);
                wmTaskItem.setProgress("20");//技术确认算完成20%
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);
            }
            wmTaskbookService.updateById(wmTaskbook);
            wmTaskbookLog.setCheckResult("技术审批已通过");

            //判断任务书当前节点是否设置过设计或工艺负责人
            if(!isTaskFlowSetChargeBy(wmTaskbook)){
                throw new RuntimeException("请先指定设计人员");
            }
        }
        else{
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_SKILL_CHANGE) || wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PLAN_APPROVED_OF_SKILL)) {
                nextStatus = UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED;
            }
            wmTaskbook.setStatus(nextStatus);
            wmTaskbook.setProgress("5");//技术审批未通过算完成5%
            //不能放到prevFlowTask()方法后面执行，不然数据又回退了，因为prevFlowTask方法里面有更改任务信息
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(nextStatus);
                wmTaskItem.setProgress("5");//技术审批未通过算完成5%
                wmTaskService.updateById(wmTaskItem);
            }

            //任务书流程部门列表，返回上一流程
            prevFlowTaskbook(wmTaskbook);
            wmTaskbookLog.setCheckResult("技术审批未通过");
        }

        if(!StringUtils.isEmpty(remark)){
            wmTaskbookLog.setContent(remark);
        }

        wmTaskbookLogService.save(wmTaskbookLog);

        //更新任务日志
        wmTaskLogService.updateTaskLog(wmTaskRoot.getId(), UserConstant.TASK_LOG_TYPE_APPROVE);

        return Result.OK("操作成功");
    }

    /**
     * 判断任务书当前节点是否设置过负责人
     */
    private boolean isTaskFlowSetChargeBy(WmTaskbook wmTaskbook){
        boolean flag = false;
        //1、通过任务书ID获取一级子任务
        LambdaQueryWrapper<WmTask> queryWrapperTask = new LambdaQueryWrapper<>();
        queryWrapperTask.eq(WmTask::getWmTaskbookId, wmTaskbook.getId()).eq(WmTask::getWmContractProductId, wmTaskbook.getWmContractProductId()).last("LIMIT 1");
        WmTask taskRoot = wmTaskService.getOne(queryWrapperTask);
        if(!StringUtils.isEmpty(taskRoot.getDesignUserId()) && taskRoot.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)){
            flag = true;
        }
        else if(!StringUtils.isEmpty(taskRoot.getProcessUserId()) && taskRoot.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)){
            flag = true;
        }
        else if(!StringUtils.isEmpty(taskRoot.getDebugUserId()) && taskRoot.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DEBUG)){
            flag = true;
        }
        else if(!StringUtils.isEmpty(taskRoot.getDesignUserId()) && taskRoot.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)){
            flag = true;
        }

        //2、任务流程列表,判断当前节点是否已指定人员
//        LambdaQueryWrapper<WmTaskFlow> queryWrapperTaskFlow = new LambdaQueryWrapper<>();
//        queryWrapperTaskFlow.eq(WmTaskFlow::getWmTaskId, taskRoot.getId());
//        List<WmTaskFlow> wmTaskFlowList = wmTaskFlowService.list(queryWrapperTaskFlow);
//        taskRoot.setWmTaskFlowList(wmTaskFlowList);
//        for(WmTaskFlow wmTaskFlow: wmTaskFlowList){
//            if(wmTaskFlow.getDepartId().equals(wmTaskbook.getCurrentNodeId()) && !StringUtils.isEmpty(wmTaskFlow.getChargeBy())){
//                flag = true;
//                break;
//            }
//        }

        return flag;
    };

    /**
     * 设计任务书提交设计(设计师提交设计给领导查看)
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务书-设计提交")
    @ApiOperation(value = "任务书-设计提交", notes = "任务书-设计提交")
    @RequiresPermissions("wmhb:wm_taskbook:designSubmit")
    @RequestMapping(value = "/designSubmit", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> designSubmit(@RequestParam(name = "id", required = true) String id) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        String nextStatus = "";
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED_OF_SKILL);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("当前状态不能提交");
        }
        if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED_OF_SKILL)){
            nextStatus = UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL;
        }
        else{
            nextStatus = UserConstant.TASK_STATUS_DESIGN_SUBMITED;
        }

        wmTaskbook.setStatus(nextStatus);
        wmTaskbook.setProgress("50");//设计已提交算完成50%
        wmTaskbookService.updateById(wmTaskbook);

        //任务书根任务状态改为和任务书状态一致
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for(WmTask wmTaskItem: wmTaskList){
            wmTaskItem.setProgress("50");//设计已提交算完成50%
            wmTaskItem.setStatus(nextStatus);
            wmTaskService.updateById(wmTaskItem);
        }

        if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)){
            if(StringUtils.isEmpty(wmTaskRoot.getDesignFile())) {
                throw new RuntimeException("请上传设计图纸");
            }
        }
        else if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)){
            List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskbookId(id);
            if(wmPurchaseTaskbookBomList.isEmpty()){
                throw new RuntimeException("请上传采购清单");
            }
        }

        return Result.OK("操作成功");
    }

    /**
     * 设计审批（领导对设计结果的审批）
     *
     * @param id
     * @param result
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-设计审批")
    @ApiOperation(value = "任务书-设计审批", notes = "任务书-设计审批")
    @RequiresPermissions("wmhb:wm_taskbook:designAapproval")
    @Transactional
    @RequestMapping(value = "/designAapproval", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> designAapproval(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "result", required = true, defaultValue = UserConstant.APPROVAL_AGREE) String result, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        String nextStatus = "";
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("设计只有设计提交状态才能审核");
        }

        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        WmTaskbookLog wmTaskbookLog = new WmTaskbookLog();
        wmTaskbookLog.setDepartId(wmTaskbook.getCurrentNodeId());
        wmTaskbookLog.setWmTaskbookId(id);
        if(!StringUtils.isEmpty(remark)){
            wmTaskbookLog.setContent(remark);
        }

        if(!StringUtils.isEmpty(result) && result.equals(UserConstant.APPROVAL_AGREE)) {
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL)){
                nextStatus = UserConstant.TASK_STATUS_DESIGN_APPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_DESIGN_APPROVED;
            }
            wmTaskbook.setStatus(nextStatus); //更新设计审批已通过
            wmTaskbook.setProgress("60");//设计审批已通过算完成60%
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("60");//设计审批已通过算完成60%
                wmTaskItem.setStatus(nextStatus);
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);
            }
            wmTaskbookLog.setCheckResult("设计审批已通过");
        }
        else{
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL)){
                nextStatus = UserConstant.TASK_STATUS_DESIGN_UNAPPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_DESIGN_UNAPPROVED;
            }
            wmTaskbook.setStatus(nextStatus); //更新设计审批未通过
            wmTaskbook.setProgress("20");//设计审批未通过算完成20%
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("20");//设计审批未通过算完成20%
                wmTaskItem.setStatus(nextStatus);
                wmTaskService.updateById(wmTaskItem);
            }
            wmTaskbookLog.setCheckResult("设计审批未通过");
        }

        //更新任务书日志
        wmTaskbookLogService.save(wmTaskbookLog);
        wmTaskbookService.updateById(wmTaskbook);

        //更新任务日志
        wmTaskLogService.updateTaskLog(wmTaskRoot.getId(), UserConstant.TASK_LOG_TYPE_DESIGN);
        return Result.OK("操作成功");
    }

    /**
     * 设计任务书提交工艺(工艺提交设计给领导查看)
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务书-工艺提交")
    @ApiOperation(value = "任务书-工艺提交", notes = "任务书-工艺提交")
    @RequiresPermissions("wmhb:wm_taskbook:processSubmit")
    @RequestMapping(value = "/processSubmit", method = {RequestMethod.PUT, RequestMethod.POST})
    @Transactional
    public Result<String> processSubmit(@RequestParam(name = "id", required = true) String id) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        String nextStatus = "";
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        //工艺是否设计提交
        Boolean bool = wmTaskService.isProcessSubmit(id);
        if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN) && !bool){
            throw new RuntimeException("请上传工艺清单");
        }

        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED);
        statusList.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_APPROVED_OF_SKILL);
        statusList.add(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED_OF_SKILL);
        statusList.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("当前状态不能提交");
        }

        //任务书状态和任务状态一致
        if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_DESIGN_APPROVED_OF_SKILL) || wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_UNAPPROVED_OF_SKILL) || wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_DESIGN_SUBMITED_OF_SKILL)) {
            nextStatus = UserConstant.TASK_STATUS_PROCESS_SUBMITED_OF_SKILL;
        }
        else{
            nextStatus = UserConstant.TASK_STATUS_PROCESS_SUBMITED;
        }
        wmTaskbook.setStatus(nextStatus);
        wmTaskbook.setProgress("70");
        wmTaskbookService.updateById(wmTaskbook);

        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for(WmTask wmTaskItem: wmTaskList){
            wmTaskItem.setProgress("70");//工艺提交算完成70%
            wmTaskItem.setStatus(nextStatus);
            wmTaskService.updateById(wmTaskItem);
        }

        return Result.OK("操作成功");
    }

    /**
     * 工艺审批通过（领导对工艺结果的审批）
     *
     * @param id
     * @param result
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-工艺审批通过")
    @ApiOperation(value = "任务书-工艺审批通过", notes = "任务书-工艺审批通过")
    @RequiresPermissions("wmhb:wm_taskbook:processApproval")
    @Transactional
    @RequestMapping(value = "/processApproval", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> processApproval(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "result", required = true, defaultValue = UserConstant.APPROVAL_AGREE) String result, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        String nextStatus = "";
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PROCESS_SUBMITED);
        statusList.add(UserConstant.TASK_STATUS_PROCESS_SUBMITED_OF_SKILL);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("设计只有工艺提交状态才能审核");
        }

        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        if(!StringUtils.isEmpty(result) && result.equals(UserConstant.APPROVAL_AGREE)) {
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_SUBMITED_OF_SKILL)){
                nextStatus = UserConstant.TASK_STATUS_PROCESS_APPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_PROCESS_APPROVED;
            }
            wmTaskbook.setStatus(nextStatus);
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("90");//工艺审批已通过算完成90%
                wmTaskItem.setStatus(nextStatus);
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
            }
            //任务书进入下一个流程
            wmTaskbook.setProgress("90");
            nextFlowTaskbook(wmTaskbook);
        }
        else{
            if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_SUBMITED_OF_SKILL)){
                nextStatus = UserConstant.TASK_STATUS_PROCESS_UNAPPROVED_OF_SKILL;
            }
            else{
                nextStatus = UserConstant.TASK_STATUS_PROCESS_UNAPPROVED;
            }
            wmTaskbook.setStatus(nextStatus);
            wmTaskbook.setProgress("70");
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setProgress("70");//工艺审批未通过算完成70%
                wmTaskItem.setStatus(nextStatus);
                wmTaskService.updateById(wmTaskItem);
            }
        }
        wmTaskbookService.updateById(wmTaskbook);

        return Result.OK("操作成功");
    }

    /**
     * 工艺审批结果回退（计划对工艺提交的结果不满意，回退到技术部）
     *
     * @param id
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-工艺审批结果回退")
    @ApiOperation(value = "任务书-工艺审批结果回退", notes = "任务书-工艺审批结果回退")
    @RequiresPermissions("wmhb:wm_taskbook:processBack")
    @Transactional
    @RequestMapping(value = "/processBack", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> processBack(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        String nextStatus = "";
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PROCESS_APPROVED);
        statusList.add(UserConstant.TASK_STATUS_PROCESS_APPROVED_OF_SKILL);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("只有工艺审核通过才能回退");
        }

        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        if(wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_APPROVED_OF_SKILL)){
            nextStatus = UserConstant.TASK_STATUS_PROCESS_SUBMITED_OF_SKILL;
        }
        else{
            nextStatus = UserConstant.TASK_STATUS_PROCESS_SUBMITED;
        }
        wmTaskbook.setStatus(nextStatus);
        wmTaskbook.setProgress("70");
        for(WmTask wmTaskItem: wmTaskList){
            wmTaskItem.setProgress("70");//回到工艺提交状态
            wmTaskItem.setStatus(nextStatus);
            wmTaskService.updateById(wmTaskItem);
        }

        //回到上一流程
        prevFlowTaskbook(wmTaskbook);

        return Result.OK("操作成功");
    }

    /**
     * 完成
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "任务书-完成")
    @ApiOperation(value = "任务书-完成", notes = "任务书-完成")
    @RequiresPermissions("wmhb:wm_taskbook:finish")
    @Transactional
    @RequestMapping(value = "/finish", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doFinish(@RequestParam(name = "ids", required = true) String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        for (String id : idList) {
            //1、更新任务书状态
            WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)){
                //设计任务书还未转换为生产任务书
                throw new RuntimeException("设计任务书还未转换为生产任务书");
            }
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)){
                //工艺任务书还未转换为采购任务书
                throw new RuntimeException("工艺任务书还未转换为采购任务书");
            }
            wmTaskbook.setStatus(UserConstant.TASK_STATUS_FINISHED); //更新任务书的状态为完成
            wmTaskbook.setProgress("100");
            wmTaskbook.setFactEndTime(new Date());
            wmTaskbookService.updateById(wmTaskbook);

            //2、任务书流程部门列表
            List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbook.getWmTaskbookFlowId());
            Integer lastIndex = wmFlowDeptList.size() - 1;
            WmFlowDept wmFlowDeptLast = wmFlowDeptList.get(lastIndex);//最后一个元素
            if(!wmFlowDeptLast.getDeptId().equals(wmTaskbook.getCurrentNodeId())){
                throw new RuntimeException("只有当前流程在最后一个节点时才能完成");
            }

            //3、获取根任务
            WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());

            //4、获取所有子任务(包括自己)，更新任务状态
            List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_FINISHED); //更新任务的状态为完成
                wmTaskItem.setCurrentNodeId(wmFlowDeptLast.getDeptId());
                wmTaskItem.setCurrentNodeIndex(lastIndex);
                wmTaskItem.setCompleteNum(wmTaskItem.getQuantity());
                wmTaskItem.setSaleNum(wmTaskItem.getQuantity());
                wmTaskItem.setProgress("100");
                if(wmTaskItem.getFactEndTime() == null) {
                    wmTaskItem.setFactEndTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);
            }

            //更新任务日志
            wmTaskLogService.updateTaskLog(wmTaskRoot.getId(), UserConstant.TASK_LOG_TYPE_PLAN_FINISH);
        }
        return Result.OK("操作成功");
    }

    /**
     * 转换任务书
     *
     * @param id
     * @param wmTaskbookFlowId
     * @return
     */
    @AutoLog(value = "任务书-转换任务书")
    @ApiOperation(value = "任务书-转换任务书", notes = "任务书-转换任务书")
    @RequiresPermissions("wmhb:wm_taskbook:transfer")
    @Transactional
    @RequestMapping(value = "/transfer", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> doTransfer(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "wmTaskbookFlowId", required = true) String wmTaskbookFlowId) {
        //1、判断状态是否可以转换
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (!wmTaskbook.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_APPROVED)) {
            throw new RuntimeException("只有工艺审核已通过状态才能转换");
        }

        //2、判断原有任务书是什么类型的任务书
        WmTaskbookFlow wmTaskbookFlowOriginal = wmTaskbookFlowService.getById(wmTaskbook.getWmTaskbookFlowId());

        //3、转换后的任务书流程
        WmTaskbookFlow wmTaskbookFlowTo = wmTaskbookFlowService.getById(wmTaskbookFlowId);
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbookFlowId);
        if (wmTaskbookFlowOriginal.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_DESIGN)) {
            if(!wmTaskbookFlowTo.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PRODUCE)) {
                throw new RuntimeException("设计任务书只能转换为生产任务书");
            }
        }
        else if (wmTaskbookFlowOriginal.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PROCESS)) {
            if(!wmTaskbookFlowTo.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)) {
                throw new RuntimeException("工艺任务书只能转换为采购任务书");
            }
        }
        else{
            throw new RuntimeException("只有设计任务书和工艺任务书才能一键转换");
        }

        //4、转换后的任务书，判断是否存在任务书，不存在则新增
        WmTaskbook wmTaskbookNew = wmTaskbookService.transferTaskbook(wmTaskbook, wmTaskbookFlowTo);

        //5、生成新任务书下所有节点的任务
        Map<String, Object> result = wmTaskService.transferTaskbook(wmTaskbook, wmTaskbookNew, wmTaskbookFlowTo);

        //6、保存任务流程
        List<WmTask> wmTaskListNew = deserializeList(result.get("list")); // 反序列化Object回List
        for(WmTask wmTask: wmTaskListNew) {
            for (WmFlowDept wmFlowDept : wmFlowDeptList) {
                WmTaskFlow wmTaskFlow = new WmTaskFlow();
                wmTaskFlow.setDepartId(wmFlowDept.getDeptId());
                wmTaskFlow.setResponsibility(wmFlowDept.getResponsibility());
                wmTaskFlow.setWmTaskId(wmTask.getId());
                wmTaskFlow.setSysOrgCode(wmFlowDept.getSysOrgCode());
                wmTaskFlow.setOrderNum(wmFlowDept.getOrderNum());
                wmTaskFlowService.save(wmTaskFlow);
            }
            //更新当前节点信息
            wmTask.setCurrentNodeId(wmFlowDeptList.get(0).getDeptId());
            wmTask.setCurrentNodeIndex(0);
            wmTask.setCurrentNodeTime(new Date());
            wmTask.setTaskbookType(wmTaskbookNew.getTaskbookType());
            wmTaskService.updateById(wmTask);
        }

        //7、修改原任务书转换状态
        WmTaskbook wmTaskbookOld = (WmTaskbook)result.get("entity");
        wmTaskbookOld.setProgress("100");
        wmTaskbookOld.setFactEndTime(new Date());
        wmTaskbookService.updateById(wmTaskbookOld);

        //8、原来任务书根任务及其子任务状态改为和任务书状态一致
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        for(WmTask wmTaskItem: wmTaskList){
            wmTaskItem.setProgress("100");
            if(wmTaskItem.getFactEndTime() == null) {
                wmTaskItem.setFactEndTime(new Date());
            }
            wmTaskItem.setCurrentNodeTime(new Date());
            wmTaskItem.setStatus(UserConstant.TASK_STATUS_FINISHED); //更新任务的状态为完成
            wmTaskService.updateById(wmTaskItem);
        }

        //9、BOM复制
        if(wmTaskbookFlowTo.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)) {
            //如果是转成采购任务书，采购BOM复制
            List<WmPurchaseTaskbookBom> wmPurchaseTaskbookBomList = wmPurchaseTaskbookBomService.listByWmTaskbookId(id);
            WmTask wmTaskRootNew = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(wmTaskbookNew.getId(), wmTaskbookNew.getCurrentVersion());
            for(WmPurchaseTaskbookBom wmPurchaseTaskbookBomItem: wmPurchaseTaskbookBomList){
                WmPurchaseTaskbookBom wmPurchaseTaskbookBom = new WmPurchaseTaskbookBom();
                BeanUtils.copyProperties(wmPurchaseTaskbookBomItem, wmPurchaseTaskbookBom);
                wmPurchaseTaskbookBom.setWmTaskbookId(wmTaskbookNew.getId());
                wmPurchaseTaskbookBom.setWmTaskId(wmTaskRootNew.getId());
                wmPurchaseTaskbookBom.setId(null);
                wmPurchaseTaskbookBomService.save(wmPurchaseTaskbookBom);
            }
        }

        //10、更新任务日志
        wmTaskLogService.updateTaskLog(wmTaskRoot.getId(), UserConstant.TASK_LOG_TYPE_PLAN_FINISH);

        return Result.OK("操作成功");
    }

    // 反序列化Object回List方法
    @SuppressWarnings("unchecked")
    private static List<WmTask> deserializeList(Object obj) {
        if (obj instanceof byte[]) {
            try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream((byte[]) obj))) {
                return (List<WmTask>) in.readObject();
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
                return null;
            }
        }
        return null;
    }

    /**
     * 根据任务书类型获取状态列表
     * @return
     */
    @ApiOperation(value = "任务书-根据任务书类型获取状态列表", notes = "任务书-根据任务书类型获取状态列表")
    @GetMapping(value = "/getStatusByType")
    public Result<List<String>> getStatusByType(@RequestParam(name = "type", required = true, defaultValue = UserConstant.TASKBOOK_TYPE_DESIGN) String type){
        List<String> list = new ArrayList<>();
        list.add(UserConstant.TASK_STATUS_PREPARE);
        list.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        if(type.equals(UserConstant.TASKBOOK_TYPE_DESIGN)){
            list.add(UserConstant.TASK_STATUS_TECHNOLOGY_APPROVED);
            list.add(UserConstant.TASK_STATUS_TECHNOLOGY_UNAPPROVED);
            list.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED);
            list.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
            list.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        }
        else if(type.equals(UserConstant.TASKBOOK_TYPE_PRODUCE)){
            list.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
            list.add(UserConstant.TASK_STATUS_PRODUCE_APPROVED);
            list.add(UserConstant.TASK_STATUS_PRODUCE_UNAPPROVED);
            list.add(UserConstant.TASK_STATUS_DESIGN_SUBMITED);
            list.add(UserConstant.TASK_STATUS_DESIGN_APPROVED);
            list.add(UserConstant.TASK_STATUS_DESIGN_UNAPPROVED);
        }
        else if(type.equals(UserConstant.TASKBOOK_TYPE_PURCHASE)){

        }
        list.add(UserConstant.TASK_STATUS_FINISHED);
        return Result.OK(list);
    }

    /**
     * 采购审批
     *
     * @param id
     * @param result
     * @param remark
     * @return
     */
    @AutoLog(value = "任务书-采购审批")
    @ApiOperation(value = "任务书-采购审批", notes = "任务书-采购审批")
    @RequiresPermissions("wmhb:wm_taskbook:purchaseApproval")
    @Transactional
    @RequestMapping(value = "/purchaseApproval", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> purchaseApproval(@RequestParam(name = "id", required = true) String id, @RequestParam(name = "result", required = true, defaultValue = UserConstant.APPROVAL_AGREE) String result, @RequestParam(name = "remark", required = false) String remark) {
        WmTaskbook wmTaskbook = wmTaskbookService.getById(id);
        if (wmTaskbook == null) {
            throw new RuntimeException("任务书不存在");
        }

        List<String> statusList = new ArrayList<>();
        statusList.add(UserConstant.TASK_STATUS_PLAN_APPROVED);
        if (!statusList.contains(wmTaskbook.getStatus())) {
            throw new RuntimeException("当前状态无法审批");
        }

        WmTaskbookLog wmTaskbookLog = new WmTaskbookLog();
        wmTaskbookLog.setDepartId(wmTaskbook.getCurrentNodeId());
        wmTaskbookLog.setWmTaskbookId(id);
        WmTask wmTaskRoot = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbook.getCurrentVersion());
        List<WmTask> wmTaskList = wmTaskService.getChildrenAsOneList(wmTaskRoot);
        if(!StringUtils.isEmpty(result) && result.equals(UserConstant.APPROVAL_AGREE)) {
            if(wmTaskbook.getTaskbookType().equals(UserConstant.TASKBOOK_TYPE_PURCHASE)){
                wmTaskbook.setStatus(UserConstant.TASK_STATUS_WAIT_PURCHASE); //待采购   采购任务书
            }
            else{
                wmTaskbook.setStatus(UserConstant.TASK_STATUS_PURCHASE_APPROVED); //更新审批已通过  调试任务书
            }
            wmTaskbook.setProgress("20");//确认算完成20%
            wmTaskbook.setFactBeginTime(new Date());
            wmTaskbook.setApproveTime(new Date());
            wmTaskbook.setAcceptDepartId(wmTaskbook.getCurrentNodeId());

            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(wmTaskbook.getStatus());
                wmTaskItem.setProgress("20");//确认算完成20%
                if(wmTaskItem.getFactBeginTime() == null) {
                    wmTaskItem.setFactBeginTime(new Date());
                }
                wmTaskService.updateById(wmTaskItem);
            }
            wmTaskbookService.updateById(wmTaskbook);
            wmTaskbookLog.setCheckResult("采购审批已通过");

            //判断任务书当前节点是否设置过调试负责人
            if(!isTaskFlowSetChargeBy(wmTaskbook)){
                throw new RuntimeException("请先指定负责人");
            }
        }
        else{
            wmTaskbook.setStatus(UserConstant.TASK_STATUS_PURCHASE_UNAPPROVED); //更新审批未通过
            wmTaskbook.setProgress("5");//审批未通过算完成5%
            //不能放到prevFlowTask()方法后面执行，不然数据又回退了，因为prevFlowTask方法里面有更改任务信息
            for(WmTask wmTaskItem: wmTaskList){
                wmTaskItem.setStatus(UserConstant.TASK_STATUS_PURCHASE_UNAPPROVED);
                wmTaskItem.setProgress("5");//审批未通过算完成5%
                wmTaskService.updateById(wmTaskItem);
            }

            //任务书流程部门列表，返回上一流程
            prevFlowTaskbook(wmTaskbook);
            wmTaskbookLog.setCheckResult("采购审批未通过");
        }

        if(!StringUtils.isEmpty(remark)){
            wmTaskbookLog.setContent(remark);
        }

        wmTaskbookLogService.save(wmTaskbookLog);

        //更新任务日志
        wmTaskLogService.updateTaskLog(wmTaskRoot.getId(), UserConstant.TASK_LOG_TYPE_APPROVE);

        return Result.OK("操作成功");
    }

    /**
     * 提交确认技改
     *
     * @param id
     * @return
     */
    @AutoLog(value = "任务书-提交确认技改")
    @ApiOperation(value = "任务书-提交确认技改", notes = "任务书-提交确认技改")
    @RequiresPermissions("wmhb:wm_taskbook:submitSkillChange")
    @Transactional
    @RequestMapping(value = "/submitSkillChange", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> submitSkillChange(@RequestParam(name = "id", required = true) String id)
    {
        WmTaskbook wmTaskbookOfDesign = wmTaskbookService.getById(id);
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        String nextVersion = format.format(new Date());
        WmTask rootTaskOfDesign = wmTaskService.getRootTaskByWmTaskbookIdAndVersion(id, wmTaskbookOfDesign.getCurrentVersion());
        if(!rootTaskOfDesign.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_APPROVED) && !rootTaskOfDesign.getStatus().equals(UserConstant.TASK_STATUS_SKILL_CHANGE) && !rootTaskOfDesign.getStatus().equals(UserConstant.TASK_STATUS_PROCESS_APPROVED_OF_SKILL)){
            return Result.error("当前状态不能确认技改");
        }

        List<WmTask> wmTaskListDesign = wmTaskService.getChildrenAsOneList(rootTaskOfDesign);
        WmTaskbook wmTaskbookOfProduce = wmTaskbookService.selectProduceTaskbookByDesignTaskbook(wmTaskbookOfDesign);
        wmTaskbookOfProduce.setCurrentVersion(nextVersion);

        //技改后的任务列表
        List<WmTask> wmTaskListNew = wmTaskService.submitSkillChange(rootTaskOfDesign, wmTaskbookOfProduce);

        //生产任务书流程，更新当前节点信息为第一个部门
        List<WmFlowDept> wmFlowDeptList = wmFlowDeptService.selectByMainId(wmTaskbookOfProduce.getWmTaskbookFlowId());
        for(WmTask wmTask: wmTaskListNew) {
            for (WmFlowDept wmFlowDept : wmFlowDeptList) {
                WmTaskFlow wmTaskFlow = new WmTaskFlow();
                wmTaskFlow.setDepartId(wmFlowDept.getDeptId());
                wmTaskFlow.setResponsibility(wmFlowDept.getResponsibility());
                wmTaskFlow.setWmTaskId(wmTask.getId());
                wmTaskFlow.setSysOrgCode(wmFlowDept.getSysOrgCode());
                wmTaskFlow.setOrderNum(wmFlowDept.getOrderNum());
                wmTaskFlowService.save(wmTaskFlow);
            }

            wmTask.setCurrentNodeId(wmFlowDeptList.get(0).getDeptId());
            wmTask.setCurrentNodeIndex(0);
            wmTaskService.updateById(wmTask);
        }

        wmTaskbookOfProduce.setCurrentNodeId(wmFlowDeptList.get(0).getDeptId());
        wmTaskbookOfProduce.setCurrentNodeIndex(0);
        wmTaskbookOfProduce.setProgress("0");
        wmTaskbookOfProduce.setStatus(UserConstant.TASK_STATUS_PREPARE);
        wmTaskbookService.updateById(wmTaskbookOfProduce);

        //技改完成
        WmSkillChange wmSkillChange = wmSkillChangeService.queryLatestRow(wmTaskbookOfDesign.getId());
        wmSkillChange.setStatus(UserConstant.TASK_STATUS_FINISHED);
        wmSkillChangeService.updateById(wmSkillChange);

        //设计任务书状态更新
        wmTaskbookOfDesign.setStatus(UserConstant.TASK_STATUS_SKILL_CHANGE_OVER);
        wmTaskbookService.updateById(wmTaskbookOfDesign);
        for(WmTask wmTask: wmTaskListDesign) {
            wmTask.setStatus(UserConstant.TASK_STATUS_SKILL_CHANGE_OVER);
            wmTaskService.updateById(wmTask);
        }
        return Result.OK("操作成功");
    }
}
